<?php 
  // Create a database connection
  $connection = mysql_connect("localhost", "cs143", "");
  if (!$connection){
    echo "Database connection failed: ". mysql_error() . "<br />";
    exit(1);
  }

  // Select a database to use
  $db_select = mysql_select_db("CS143", $connection);
  if (!$db_select){
    echo "Database selection faild: " . mysql_error() . "<br />";
    exit(1);
  }
?> 
<html>
  <head>
    <title>Query</title>
  </head>
  <h2>Project 1B</h2>
  By: Gabriel Lopez and Jose Rodriguez Salinas<br /><br />
  <body>
  <form method="POST">
  <textarea name="query" cols="60" rows="8"><?php $input = $_POST["query"];
      echo $input;  
    ?></textarea>
  <input type="submit" value="Submit" />
  </form>
  <h3>Results from MySQL:</h3>

  <?php
  preg_match("#^\ *((select)|(show))#i", $input, $matches);
  if($matches[0] == "" && $input != "")
  {
    echo "Sorry, only SELECT and SHOW queries are allowed!";
    exit(1);
  }

  // Perform database query
  $sanitized_name = mysql_real_escape_string($input, $connection);
  $query_to_issue = sprintf($input, $sanitized_name);
  $result = mysql_query($query_to_issue, $connection);
  if(!$result && $input != ""){
    echo mysql_error($connection);
    exit(1);
  }

  // Use returned data
  if($result != NULL && $row = mysql_fetch_array($result))
  {
    echo "<table border=1 cellspacing=1 cellpadding=2>";
    $col = array_keys($row);
    echo "<tr align=center>";
    for($j=1; $j < sizeof($col); $j+=2)
    {
      echo "<td><b>" . $col[$j] . "</b></td>";
    }
    echo "</tr>";
  do{
    echo "<tr align=center>";
    for($i = 0; $i < sizeof($row)/2; $i++)
    {	      
      echo "<td>";
      if($row[$i] == NULL)
        echo "N/A";
      else
        echo $row[$i];
      echo "</td>";
    }
    echo "</tr>";
  } while ($row = mysql_fetch_array($result));
  echo "</table>";
  }
  
  ?>
  </body>
</html> 
<?php
  // Close connection
  mysql_close($connection);
?>
